program List2;


{$APPTYPE CONSOLE}

uses
  SysUtils;

type  
  pelement = ^element;
  element = record
    value : Integer;
    next : pelement;
  end;



procedure AddToBegin (var head : pelement; num : integer);
  var tmp : pelement;
  begin
      tmp := head;
      New (head);
      head^.value := num;
      head^.next := tmp;
  end;

function DeleteFromBegin (var head : pelement):integer;
  var tmp : pelement;
  begin
      if (head <> nil) then
      begin
          tmp := head^.next;
          DeleteFromBegin := head^.value;
          Dispose (head);
          head := tmp;
      end;
  end;

procedure PrintList (head : pelement);
  var current : pelement;
  begin
    current := head;
    while (current <> nil) do
    begin
        Writeln (current^.value);
        current := current^.next;
    end;
  end;

procedure AddToEnd (head : pelement; num : integer);
  var current : pelement;
  begin
    if (head <> nil) then
    begin
      current := head;
      while (current^.next <> nil) do
      begin

        current := current^.next;
        new (current^.next);
        current^.next.next := nil;
        current^.next^.value := num;
      end;
    end else
    begin
      AddToBegin(head, num);
    end;
    end;

  procedure DeleteFromEnd (var head : pelement);
  begin
    if (head<>nil) then
    if (head^.next=nil) then
    DeleteFromBegin(head)
    else
    DeleteFromEnd(head^.next);
  end;

var
  n, i, a: integer;
  fin : textfile;
  head : pelement;

begin
  assignfile (fin, 'input.txt');
  Reset (fin);
  Read(fin, n);
  for I := 0 to 4 do
  begin
    read (fin, a);
   DeleteFromBegin(head);
  end;

  PrintList(head);

  for i := 0 to 4 do
  begin
  DeleteFromEnd(head);
  end;


  PrintList(head);
  Readln;
     CloseFile (fin);
  Readln;
end.

